package com.bulletelc.apollopre.wxapi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.eventbus.EventBusEvent;
import com.bulletelc.apollopre.utils.LogUtil;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;

/**
 * author: lhl
 * date  : 2018/01/21
 * desc  : 微信支付的回调
 */

public class WXPayEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private IWXAPI iwxapi;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //iwxapi = MyApplication.getInstance().getIwxapi();
        iwxapi = WXAPIFactory.createWXAPI(this, GlobalConfig.WX_API_APP_ID);
        iwxapi.handleIntent(getIntent(), this);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        iwxapi.handleIntent(intent, this);
    }

    /**
     * @param baseReq
     */
    @Override
    public void onReq(BaseReq baseReq) {
        LogUtil.i("openId=" + baseReq.openId +
                "\ntype=" + baseReq.getType() +
                "\ntransaction=" + baseReq.transaction +
                "\ncheckArgs=" + baseReq.checkArgs() +
                "\ntoString=" + baseReq.toString()
        );
    }

    /**
     * 发送到微信请求的响应结果将回调到onResp方法
     *
     * @param baseResp
     */
    @Override
    public void onResp(BaseResp baseResp) {
//        LogUtil.i("openId=" + baseResp.openId +
//                "\ntype=" + baseResp.getType() +
//                "\ntransaction=" + baseResp.transaction +
//                "\ncheckArgs=" + baseResp.checkArgs() +
//                "\nerrCode=" + baseResp.errCode +
//                "\nerrStr=" + baseResp.errStr +
//                "\ntoString=" + baseResp.toString()
//        );

        if (baseResp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {

            EventBusEvent event = new EventBusEvent();
            event.setWxPayErrCode(baseResp.errCode);
            EventBus.getDefault().post(event);//发布事件

            finish();
        }
    }
}
